# -*-coding:utf-8 -*-
import re
from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from forfood.customer.models import *
from django.contrib.auth import authenticate

class LoginForm(forms.Form):
    email = forms.EmailField(label='Email')
    password = forms.CharField(label='密码', widget=forms.PasswordInput())
    
    def get_user(self):
        return authenticate(username=self.cleaned_data['email'], 
                            password=self.cleaned_data['password'])
    def clean_email(self):
        email = self.data['email']
        try:
            User.objects.get(email=email)
        except ObjectDoesNotExist:
            raise forms.ValidationError('该Email尚未注册.')
        return email
    
        
    
class RegistrationForm(forms.Form):
    email = forms.EmailField(label='Email')
    name = forms.CharField(label='姓名', max_length=30)    
    password1 = forms.CharField(
        label='密码',
        widget=forms.PasswordInput()
        )
    password2 = forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput()
        )

    def clean_password2(self):
        if 'password1' in self.data:
            password1 = self.data['password1']
            password2 = self.data['password2']
            if password1 == password2:
                return password2
        raise forms.ValidationError('两次输入的密码不一致.')

    
    def clean_email(self):
        email = self.data['email']
        try:
            User.objects.get(email=email)
        except ObjectDoesNotExist:
            return email
        raise forms.ValidationError('该Email已注册.')
    
    def save(self):
        customer = Customer.objects.create(name=self.cleaned_data['name'],
                                           username=self.cleaned_data['email'],
                                           email=self.cleaned_data['email'],
                                           password=self.cleaned_data['password1'],
                                           address=Address.objects.get(more='None'),
                                           is_active=False)
        customer.set_password(self.cleaned_data['password1'])
        customer.save()
        return customer

                                        